<template>
  <el-form-item :label="eventNameText">
    <el-button style="flex: 1" plain @click="dialogCode = true">编辑事件</el-button>
  </el-form-item>

  <el-dialog
    v-model="dialogCode"
    title="编辑事件"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <el-alert type="info" :closable="false" :title="eventHeader" />
    <code-editor v-model="eventCode" mode="javascript" />
    <el-alert type="info" :closable="false" title="}" />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleSave">确定</el-button>
        <el-button @click="dialogCode = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { computed, ref, watch } from 'vue'

export default {
  props: {
    name: {
      type: String,
      default: ''
    },
    eventName: {
      type: String,
      default: null
    },
    eventParams: {
      type: Array,
      default: null
    },
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const dialogCode = ref(false)
    const eventCode = ref('')

    watch(
      () => props.modelValue,
      (value) => {
        eventCode.value = value
      },
      { immediate: true }
    )

    const eventHeader = computed(() => {
      let parms = ''
      if (props.eventParams) {
        parms = props.eventParams.join(', ')
      }
      return `${props.name}.${props.eventName}(${parms}) {`
    })

    const eventNameText = computed(() => {
      if (props.eventName === 'onValidate') {
        return '校验后触发'
      }
      if (props.eventName === 'onChange') {
        return '值发生改变'
      }
      if (props.eventName === 'onClick') {
        return '元素被点击'
      }
      if (props.eventName === 'onFocus') {
        return '获得焦点时'
      }
      if (props.eventName === 'onBlur') {
        return '失去焦点后'
      }
      return props.eventName
    })

    const handlerShow = () => {
      dialogCode.value = true
    }

    const handleSave = () => {
      emit('update:modelValue', eventCode.value)
      dialogCode.value = false
    }

    return {
      dialogCode,
      eventCode,
      eventHeader,
      eventNameText,
      handlerShow,
      handleSave
    }
  }
}
</script>

<style lang="scss">
.ep-eventItem {
  margin-bottom: 0;

  .el-form-item__label {
    flex: 1;
    justify-content: flex-end;
    padding-right: 100px;
  }
  .el-form-item__content {
    justify-content: flex-end;
    padding-right: 30px;
  }
}
</style>
